import * as vscode from 'vscode';
import { SettingsReader } from './settingsReader';
import { CSSParser } from './cssParser';

/**
 * CSS类名自动补全提供器
 * 为HTML/Vue/TSX文件提供CSS类名自动补全功能
 */
export class CSSClassProvider implements vscode.CompletionItemProvider {
    private settingsReader: SettingsReader;
    private cssParser: CSSParser;

    constructor(settingsReader: SettingsReader, cssParser: CSSParser) {
        this.settingsReader = settingsReader;
        this.cssParser = cssParser;
        
        // 初始化时刷新CSS类名
        this.cssParser.refreshCSSClasses();
    }

    /**
     * 提供自动补全项
     * @param document 当前文档
     * @param position 光标位置
     * @param token 取消令牌
     * @param context 补全上下文
     * @returns 补全项数组
     */
    public async provideCompletionItems(
        document: vscode.TextDocument,
        position: vscode.Position,
        token: vscode.CancellationToken,
        context: vscode.CompletionContext
    ): Promise<vscode.CompletionItem[] | vscode.CompletionList | undefined> {
        
        // 检查是否在class属性中
        const classContext = this.isInClassAttribute(document, position);
        
        if (!classContext.isInClass) {
            return undefined;
        }

        // 获取当前输入的前缀
        const currentPrefix = this.getCurrentPrefix(document, position, classContext);
        
        // 获取配置的前缀列表
        const configuredPrefixes = this.settingsReader.getPrefixes();
        
        // 检查当前输入是否匹配配置的前缀
        const matchingPrefix = configuredPrefixes.find(prefix => 
            currentPrefix.startsWith(prefix)
        );

        if (!matchingPrefix) {
            return undefined;
        }

        // 获取CSS类名
        const cssClasses = this.cssParser.getClassesByPrefix(matchingPrefix);
        
        // 创建补全项
        const completionItems: vscode.CompletionItem[] = cssClasses.map(className => {
            const item = new vscode.CompletionItem(className, vscode.CompletionItemKind.Class);
            item.detail = 'CSS类名';
            item.documentation = `CSS类: ${className}`;
            item.insertText = className;
            item.sortText = className;
            return item;
        });

        return completionItems;
    }

    /**
     * 检查光标是否在class属性中
     * @param document 文档
     * @param position 位置
     * @returns 检查结果
     */
    private isInClassAttribute(document: vscode.TextDocument, position: vscode.Position): {
        isInClass: boolean;
        attributeStart?: vscode.Position;
        attributeEnd?: vscode.Position;
        attributeName?: string;
    } {
        const line = document.lineAt(position.line);
        const text = line.text;
        const charIndex = position.character;

        // 检查class属性（HTML/Vue）
        const classRegex = /class\s*=\s*["']([^"']*)["']/g;
        let match;

        while ((match = classRegex.exec(text)) !== null) {
            const startIndex = match.index + match[0].indexOf(match[1]);
            const endIndex = startIndex + match[1].length;

            if (charIndex >= startIndex && charIndex <= endIndex) {
                return {
                    isInClass: true,
                    attributeStart: new vscode.Position(position.line, startIndex),
                    attributeEnd: new vscode.Position(position.line, endIndex),
                    attributeName: 'class'
                };
            }
        }

        // 检查className属性（React/TSX）
        const classNameRegex = /className\s*=\s*["']([^"']*)["']/g;
        match = null;

        while ((match = classNameRegex.exec(text)) !== null) {
            const startIndex = match.index + match[0].indexOf(match[1]);
            const endIndex = startIndex + match[1].length;

            if (charIndex >= startIndex && charIndex <= endIndex) {
                return {
                    isInClass: true,
                    attributeStart: new vscode.Position(position.line, startIndex),
                    attributeEnd: new vscode.Position(position.line, endIndex),
                    attributeName: 'className'
                };
            }
        }

        return { isInClass: false };
    }

    /**
     * 获取当前输入的前缀
     * @param document 文档
     * @param position 位置
     * @param classContext class属性上下文
     * @returns 当前前缀
     */
    private getCurrentPrefix(
        document: vscode.TextDocument, 
        position: vscode.Position, 
        classContext: { attributeStart?: vscode.Position; attributeEnd?: vscode.Position; attributeName?: string }
    ): string {
        if (!classContext.attributeStart) {
            return '';
        }

        const line = document.lineAt(position.line);
        const text = line.text;
        const startIndex = classContext.attributeStart.character;
        const currentIndex = position.character;

        // 获取从属性开始到当前位置的文本
        const prefixText = text.substring(startIndex, currentIndex);
        
        // 查找最后一个空格或开始位置
        const lastSpaceIndex = prefixText.lastIndexOf(' ');
        const actualStartIndex = lastSpaceIndex === -1 ? 0 : lastSpaceIndex + 1;
        
        return prefixText.substring(actualStartIndex);
    }

    /**
     * 解析补全项
     * @param item 补全项
     * @param token 取消令牌
     * @returns 解析后的补全项
     */
    public resolveCompletionItem(
        item: vscode.CompletionItem,
        token: vscode.CancellationToken
    ): vscode.ProviderResult<vscode.CompletionItem> {
        return item;
    }
}
